package com.hefan.api.controller.oms;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.bean.Message;
import com.hefan.common.ons.service.ONSProducer;
import com.hefan.common.util.DynamicProperties;
import com.hefan.common.util.HttpUtils;
import com.hefan.oms.bean.Present;
import com.hefan.oms.bean.RebalanceVo;
import com.hefan.oms.itf.PresentService;
import com.hefan.pay.bean.CurrentTypePrice;
import com.hefan.pay.itf.CurrentRechargeService;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WebUserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by hbchen on 2016/9/29.
 */
@Controller
@RequestMapping("v1/user")
public class ReBalanceController {
  /*@Resource
  RebalanceLocalService rebalanceLocalService;*/
  @Reference
  ONSProducer onsProducer;
  @Reference
  private WebUserService webUserService;
  @Reference
  CurrentRechargeService  currentRechargeService;
  @Reference
  PresentService presentService;


  Logger logger = LoggerFactory.getLogger(ReBalanceController.class);

  @RequestMapping(value="/rebalance",method= RequestMethod.GET)
  @ResponseBody
  public ResultBean rebalance(HttpServletRequest request) {

    RebalanceVo rebalanceVo = HttpUtils.initParam(request,RebalanceVo.class);
    logger.info("扣费controller 参数{}",JSON.toJSONString(rebalanceVo));

        /*校验参数是否合法*/

    if(rebalanceVo == null) {
      return new ResultBean(ResultCode.ParamException.get_code(), "参数有空格");
    }

    if(StringUtils.isBlank(rebalanceVo.getFromId())){
      return new ResultBean(ResultCode.ParamException.get_code(), "fromId有误");
    }
    if(StringUtils.isBlank(rebalanceVo.getToId())){
      return new ResultBean(ResultCode.ParamException.get_code(), "toId有误");
    }
    //自己给自己发礼物
    if(rebalanceVo.getFromId().equals(rebalanceVo.getToId())){
      return new ResultBean(ResultCode.ParamException.get_code(), "自己不能给自己发礼物");
    }

    if (rebalanceVo.getPrice()<0 ){
      return new ResultBean(ResultCode.ParamException.get_code(), "Price有误");
    }
    if (rebalanceVo.getPresentId() <= 0){
      return new ResultBean(ResultCode.ParamException.get_code(), "PresentId有误");
    }

    if (rebalanceVo.getSource()<0 ){
      return new ResultBean(ResultCode.ParamException.get_code(), "Source有误");
    }else if(rebalanceVo.getSource() == GlobalConstants.SOURCE_TYPE_LIVE){
      //除了直播间送礼物，其他的不用传礼物名称
      if(StringUtils.isBlank(rebalanceVo.getPresentName())){
        return new ResultBean(ResultCode.ParamException.get_code(), "PresentName有误");
      }

      if(StringUtils.isBlank(rebalanceVo.getNickName())){
        return new ResultBean(ResultCode.ParamException.get_code(), "NickName有误");
      }
      if(StringUtils.isBlank(rebalanceVo.getRoomId())){
        return new ResultBean(ResultCode.ParamException.get_code(), "RoomId有误");
      }
      if (rebalanceVo.getPresentNum() <= 0){
        return new ResultBean(ResultCode.ParamException.get_code(), "PresentNum有误");
      }
      if (StringUtils.isBlank(rebalanceVo.getLiveUuid())){
        return new ResultBean(ResultCode.ParamException.get_code(), "liveuuid有误");
      }

    }else if(rebalanceVo.getSource() == GlobalConstants.SOURCE_TYPE_BARRAGE){
      if(StringUtils.isBlank(rebalanceVo.getContent())){
        return new ResultBean(ResultCode.ParamException.get_code(), "content有误");
      }
      if(StringUtils.isBlank(rebalanceVo.getRoomId())){
        return new ResultBean(ResultCode.ParamException.get_code(), "RoomId有误");
      }
      rebalanceVo.setPresentName("弹幕");
    }else if(rebalanceVo.getSource() == GlobalConstants.SOURCE_TYPE_MESSAGE){
      if(StringUtils.isBlank(rebalanceVo.getContent())){
        return new ResultBean(ResultCode.ParamException.get_code(), "content有误");
      }
      rebalanceVo.setPresentName("私信");
    }

    try {
      WebUser fromUser =  webUserService.getWebUserInfoByUserId(rebalanceVo.getFromId());
      if (fromUser==null){
        return new ResultBean(ResultCode.UNSUCCESS.get_code(), "扣费用户不存在");
      }
      rebalanceVo.setBeforeFanpiao(fromUser.getBalance());//记录扣款前余额
      rebalanceVo.setUserType(fromUser.getUserType());
      if (rebalanceVo.getSource() == GlobalConstants.SOURCE_TYPE_LIVE) {
        Present present = presentService.getPresentById(rebalanceVo.getPresentId());
        if (present==null){
          return new ResultBean(ResultCode.UNSUCCESS.get_code(), "礼物设置有误");
        }

        if(present.getPrice()<=0){
          return new ResultBean(ResultCode.UNSUCCESS.get_code(), "价格设置有误");
        }

        if (present.getPrice() != rebalanceVo.getPrice()) {
          return new ResultBean(ResultCode.RebalancePriceIsValid.get_code(), "价格有误");
        }

        if(present.getType()<0){
          return new ResultBean(ResultCode.UNSUCCESS.get_code(), "类型设置有误");
        }

        if(present.getIscontinue()<0){
          return new ResultBean(ResultCode.UNSUCCESS.get_code(), "连发设置有误");
        }
        rebalanceVo.setExp(present.getExperience());
        rebalanceVo.setPresentName(present.getPresentName());
        rebalanceVo.setPrice(present.getPrice());
        //先判断账户余额是否充足
        long balance = present.getPrice()  ;
        if (fromUser.getBalance()<balance) {
          logger.error("用户{}扣费余额{}不足本次{}",fromUser.getUserId(), fromUser.getBalance(),balance);
          return new ResultBean(ResultCode.RebalanceBalanceNotEnough.get_code(),"余额不足");
        }
        if ((present.getType() == GlobalConstants.PRESENT_TYPE_BIG
            || present.getType()== GlobalConstants.PRESENT_TYPE_WORLD
            || present.getType()== GlobalConstants.PRESENT_TYPE_SMALL )
            && present.getIscontinue()==GlobalConstants.PRESENT_ISNOTCONTINUE) {
          //因为是扣费操作，乘以-1连发的不在主线程做扣费
            webUserService.incrWebUserBalance(rebalanceVo.getFromId(), -1 * balance);
        }else {
          if(StringUtils.isBlank(rebalanceVo.getUniqueKey())){
            return new ResultBean(ResultCode.ParamException.get_code(), "uniqueKey有误");
          }
        }
        logger.info("present.getType()"+present.getType());
        logger.info("present.getIscontinue()"+present.getIscontinue());
        rebalanceVo.setHoutaiPresentType(present.getType());
        rebalanceVo.setIsContinue(present.getIscontinue());

      }else if (rebalanceVo.getSource() == GlobalConstants.SOURCE_TYPE_MESSAGE) {
        logger.error("私信扣费参数{}",JSON.toJSONString(rebalanceVo));

        CurrentTypePrice currentTypePrice =  currentRechargeService.findCurrentPriceById((int)rebalanceVo.getPresentId());
        if (currentTypePrice==null || currentTypePrice.getPrice() != rebalanceVo.getPrice() ){
          return new ResultBean(ResultCode.UNSUCCESS.get_code(), "价格有误");
        }
        //私信扣费
        int price  = currentTypePrice.getPrice();

        rebalanceVo.setPrice(0);
        if(fromUser.getUserType()==GlobalConstants.USER_TYPE_USER || fromUser.getUserType()==GlobalConstants.USER_TYPE_FLASE
            || fromUser.getUserType()==GlobalConstants.USER_TYPE_BROKER || fromUser.getUserType()==GlobalConstants.USER_TYPE_INNER){
          //校验发送者用户等级,22级可发私信网红，32级可发私信明星和片场
          int level=fromUser.getUserLevel();
          if(level<22){
            return new ResultBean(ResultCode.UNSUCCESS.get_code(), "用户等级不满22级");
          }
          //私信接收者,身份是明星或片场,判断用户等级是否满足32级
          WebUser user=webUserService.getWebUserInfoByUserId(rebalanceVo.getToId());
          if((user.getUserType()==GlobalConstants.USER_TYPE_SITE || user.getUserType()==GlobalConstants.USER_TYPE_STAR)&&level<32){
            return new ResultBean(ResultCode.UserLevelInsufficient.get_code(), "用户等级不满32级，不能和明星私信");
          }

          if ( fromUser.getBalance() >= price) {
            rebalanceVo.setPrice(price);
            webUserService.incrWebUserBalance(rebalanceVo.getFromId(), -1 * price);
          } else {
            return new ResultBean(ResultCode.RebalanceBalanceNotEnough.get_code(), "余额不足");
          }
        }else if (fromUser.getUserType()==GlobalConstants.USER_TYPE_FAMOUS){
          WebUser toUser =  webUserService.getWebUserInfoByUserId(rebalanceVo.getToId());
          logger.info("网红{}给{}-{}发私信",fromUser.getUserId(),toUser.getUserId(),toUser.getUserType());
          if (toUser.getUserType()==GlobalConstants.USER_TYPE_SITE || toUser.getUserType()==GlobalConstants.USER_TYPE_STAR){
            if (fromUser.getBalance() >= price) {
              rebalanceVo.setPrice(price);
              webUserService.incrWebUserBalance(rebalanceVo.getFromId(), -1 * price);
            } else {
              return new ResultBean(ResultCode.RebalanceBalanceNotEnough.get_code(), "余额不足");
            }

          }
        }


      }else if (rebalanceVo.getSource() == GlobalConstants.SOURCE_TYPE_BARRAGE) {

        int price = 0;
        CurrentTypePrice currentTypePrice =  currentRechargeService.findCurrentPriceById((int)rebalanceVo.getPresentId());
        if (currentTypePrice==null || currentTypePrice.getPrice() != rebalanceVo.getPrice() ){
          return new ResultBean(ResultCode.UNSUCCESS.get_code(), "价格有误");
        }else{
          price = currentTypePrice.getPrice();
        }

        if (price <= 0){
          return new ResultBean(ResultCode.UNSUCCESS.get_code(), "价格有误");
        }

        if (fromUser.getBalance() >= price) {
          webUserService.incrWebUserBalance(rebalanceVo.getFromId(), -1 * price);
        } else {
          return new ResultBean(ResultCode.RebalanceBalanceNotEnough.get_code(), "余额不足");
        }
      }


      // 给队列发消息，完成后续工作
      String onsEnv = DynamicProperties.getString("ons.env");

      Message messageOrder = new Message();
      messageOrder.setTag(onsEnv);
      messageOrder.put("rebalanceVoOrder", JSON.toJSONString(rebalanceVo));
      messageOrder.setTopic(TopicRegistry.HEFAN_ORDER);
      onsProducer.sendMsg(messageOrder);

      // 给队列发消息，完成后续工作
      Message message = new Message();
      message.setTag(onsEnv);
      message.put("rebalanceVo", JSON.toJSONString(rebalanceVo));
      message.setTopic(TopicRegistry.HEFANTV_OMS);
      onsProducer.sendMsg(message);



    }catch (Exception e){
      logger.error(e.getMessage());
      return new ResultBean(ResultCode.UNSUCCESS.get_code(),ResultCode.UNSUCCESS.getMsg());
    }

    return new ResultBean(ResultCode.SUCCESS.get_code(),ResultCode.SUCCESS.getMsg());
  }
}
